from sqlalchemy import func
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.mutable import MutableDict
from core.file.helpers import get_signed_file_url
from models.engine import db
from models.robot.rob_emoji import RobEmojiPack
from models.robot.rob_timbre import RobTimbre
from models.types import StringUUID


class RobCharacter(db.Model):
    __tablename__ = "rob_characters"
    __table_args__ = (
        db.PrimaryKeyConstraint('id', name='rob_characters_pk'),
        db.Index('idx_rob_characters_tenant', 'tenant_id'),
    )
    id: Mapped[str] = mapped_column(
        StringUUID, server_default=db.text("uuid_generate_v4()"),)
    tenant_id = db.Column(StringUUID, nullable=False)
    name = db.Column(db.String(128), nullable=False, comment="名称")
    agent_id = db.Column(StringUUID, nullable=False, comment="对应智能体ID")
    personality = db.Column(db.String(512), nullable=False, comment="个性描述")
    config = db.Column(MutableDict.as_mutable(JSONB), nullable=True,server_default=db.text("'{}'::jsonb"),comment="配置")
    price = db.Column(db.Integer, nullable=False, default=0, comment="价格/分")
    default_timbre_id = db.Column(StringUUID, nullable=True,)
    default_emoji_pack_id = db.Column(StringUUID, nullable=True,)
    created_at = db.Column(db.DateTime, nullable=False,
                           server_default=func.current_timestamp(), comment="创建时间")
    created_by = db.Column(StringUUID, nullable=False, comment="创建人")
    updated_at = db.Column(db.DateTime, nullable=True,
                           server_default=func.current_timestamp())
    updated_by = db.Column(StringUUID, nullable=True,)
    def to_dict(self)->dict:
        return {
            "id":self.id,
            "name":self.name,
            "personality":self.personality,
            "agent_id":self.agent_id,
            "default_timbre_id":self.default_timbre_id,
            "price":self.price,
        }
    
    @property
    def default_timbre(self)->RobTimbre|None:
        if self.default_timbre_id:
            return db.session.get(RobTimbre, self.default_timbre_id)
        return None
    
    @property
    def default_emoji_pack(self)->RobEmojiPack|None:
        if self.default_emoji_pack_id:
            return db.session.get(RobEmojiPack, self.default_emoji_pack_id)
        return None
    
    @property
    def appearance_url(self)->str|None:
        if self.config:
            return self.config.get("appearance_url",None)
        return None
    
    @appearance_url.setter
    def appearance_url(self,value:str):
        self.config = self.config or {}
        self.config["appearance_url"] = value

    @property
    def appearance_file_id(self)->str|None:
        if self.config:
            return self.config.get("appearance_file_id",None)
        return None
    
    @appearance_file_id.setter
    def appearance_file_id(self,value:str):
        self.config = self.config or {}
        self.config["appearance_file_id"] = value

    @property
    def appearance_file_url(self)->str|None:
        if self.config:
            file_id = self.config.get("appearance_file_id",None)
            if file_id:
                return get_signed_file_url(file_id)
        return None

    @property
    def greet_sentence(self)->str|None:
        if self.config:
            return self.config.get("greet_sentence",None)
        return None
    
    @greet_sentence.setter
    def greet_sentence(self,value:str):
        self.config = self.config or {}
        self.config["greet_sentence"] = value

    @property
    def wakeup_sentences(self)->list[str]:
        if self.config:
            return self.config.get("wakeup_sentence",[])
        return []
    
    @wakeup_sentences.setter
    def wakeup_sentences(self,value:list[str]):
        self.config = self.config or {}
        self.config["wakeup_sentence"] = value

    @property
    def busy_sentences(self)->list[str]:
        if self.config:
            return self.config.get("busy_sentences",[])
        return []
    
    @busy_sentences.setter
    def busy_sentences(self,value:list[str]):
        self.config = self.config or {}
        self.config["busy_sentences"] = value

    @property
    def stepback_sentences(self)->list[str]:
        if self.config:
            return self.config.get("stepback_sentences",[])
        return []
    
    @stepback_sentences.setter
    def stepback_sentences(self,value:list[str]):
        self.config = self.config or {}
        self.config["stepback_sentences"] = value

    @property
    def Price(self)->float:
        if self.price>0:
            return self.price*(1.0/1000.0)
        return 0
    
class RobCharacterHVERMap(db.Model):
    __tablename__ = "rob_char_hver_map"
    __table_args__ = (
        db.PrimaryKeyConstraint('character_id', 'hver',
                                name='idx_rob_char_hver_map_pk'),
        db.Index('idx_rob_char_hver_map_hver', 'hver'),
    )
    hver = db.Column(db.String(32), nullable=False, comment="硬件版本")
    character_id = db.Column(StringUUID, nullable=False, comment="角色ID")
    created_at = db.Column(db.DateTime, nullable=False,
                           server_default=func.current_timestamp(), comment="创建时间")
    created_by = db.Column(StringUUID, nullable=False, comment="创建人")
